import axios from "axios";
import runtime_config from "./config";
import message from "./message.js";
import store from '../common/store.js';
import common from '../common/common.js';
import date from "../common/date.js";
import COS from 'cos-js-sdk-v5';

let cos = new COS({
	SecretId: 'AKIDvhHhyU3VnyxkMpCOOGzWq6LPH0cCdvDU',
	SecretKey: 'KYcaO0Tp5C8wZ0GLH5iAUglgQ2VounT5',
});

axios.defaults.withCredentials = true;
axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
axios.defaults.headers.put["Content-Type"] = "application/x-www-form-urlencoded";
// axios.defaults.headers.put["Content-Type"] = "application/json";

let _instance = axios.create({
	withCredentials: true,
	baseURL: runtime_config[process.env.NODE_ENV].path,
});

_instance.interceptors.request.use(
    config => {
		
		let TOKEN = common.getAttribute("TOKEN");
		
		if (TOKEN) {
			config.headers.token = TOKEN;
		}

        return config;
    },
    error => {
        console.log(error);
        return Promise.reject(error);
    });



const httpObject = {
	_changeParam: param => {
		if (process.env.NODE_ENV !== "local") {
			if (param.param) {
				param.params = param.param;
			}
			
			if (param.data) {
				param.data = param.data;
			}
		}
		return param;
	},
	uploadFile: function(coverFileObject) {
		
		if (coverFileObject.path) {
			
		} else {
			coverFileObject.path = "store/fm/";
		}
	
		return new Promise((success, error) => {
			cos.putObject({
				Bucket: '',
				/* 填入您自己的存储桶，必须字段 */
				Region: 'ap-nanjing',
				/* 存储桶所在地域，例如ap-beijing，必须字段 */
				Key: coverFileObject.path+date.formatDate(new Date(), "yyyy/MM/dd")+"/"+coverFileObject.file.name,
				/* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
				StorageClass: 'STANDARD',
				Body: coverFileObject.file, // 上传文件对象
				onProgress: function(progressData) {
					coverFileObject.onProgress(progressData);
				}
			}, function(err, data) {
				if (err) {
					error(err);
				}
	
				if (data) {
					success(data);
				}
			});
		});
	
	},
	put: param => {
		param.method = "put";
		return httpObject._request(httpObject._changeParam(param));
	},
	get: param => {
		param.method = "get";
		return httpObject._request(httpObject._changeParam(param));
	},
	post: param => {
		param.method = "post";
		return httpObject._request(httpObject._changeParam(param));
	},
	"delete": param => {
		param.method = "delete";
		return httpObject._request(httpObject._changeParam(param));
	},
	_request: param => {
		return new Promise((resolve, reject) => {
			
			
			_instance.request(param)
				.then(res => {
					if (res.headers.token) {
						common.setAttribute("TOKEN", res.headers.token);
					}
					
					let response = typeof res === "string" ? JSON.parse(res) : res;
					let responseData = response.data;
					let status = responseData.STATUS;

					if ("SUCCESS" === status) {
						resolve(responseData.DATA);
					} else if (status === "NOT_LOGIN") {
						store.commit('loginOut');
					} else if (status === "FAIL") {
						message.warning(responseData.MESSAGE);
					} else if (status === "ERROR") {
						message.error(responseData.MESSAGE);
					} else {
						message.error("系统出现未知错误。");
					}
				})
				.catch(err => {
					console.log(err);
					message.error("系统出现未知错误！");
				});
		});
	}
}



export default httpObject;
